﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace EnterAndQuit
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillData();
            }

        }

        protected void gv1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gv1.EditIndex = -1;
            FillData();
        }
        //删除
        protected void gv1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetCellValue(e.RowIndex, 0);
            var sql = string.Format("delete Users where id ='{0}'", id);
            DbHelper.AddOrUpdateOrDelete(sql);
            gv1.EditIndex = -1;
            FillData();
        }

        protected void gv1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gv1.EditIndex = e.NewEditIndex;
            FillData();

        }
        //更新
        protected void gv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var id = GetCellValue(e.RowIndex, 0);
            var username = GetCellValue(e.RowIndex, 1);
            var password = GetCellValue(e.RowIndex, 2);
            var remarks = GetCellValue(e.RowIndex, 3);
            var sql = string.Format("update Users set Username='{0}',password='{1}',remarks='{2}'where Id={3}", username, password, remarks, id);
            DbHelper.AddOrUpdateOrDelete(sql);
            gv1.EditIndex = -1;
            FillData();
        }

        private string GetCellValue(int rowIndex,int colIndex)
        {
            var control = gv1.Rows[rowIndex].Cells[colIndex];
            var res = control.Controls.Count > 0 ? ((TextBox)control.Controls[0]).Text : control.Text;
            return res;    
        }



        public void FillData()
        {
            var X = "select Id,Username,password,remarks from Users";
            var dt = DbHelper.GetData(X);

            gv1.DataSource = dt;
            gv1.DataBind();
        }
    }
}